#ifndef UDPRECEIVER_H
#define UDPRECEIVER_H

#include <vector>
#include <functional> // 用于 std::function
#include <iostream>
#include <boost/asio.hpp>

using DatagramReceived = std::function<void(const std::vector<uint8_t> &)>;
//using DatagramReceived = std::function<void(const std::vector<uint8_t> &, const boost::asio::ip::udp::endpoint &)>;
// using DatagramReceived = void (*)(const std::vector<uint8_t> &data, const boost::asio::ip::udp::endpoint &endpoint);

class UdpReceiver
{
public:
    UdpReceiver(const std::string &bindIP, const std::string &remoteIP, unsigned short port);
    ~UdpReceiver();

    bool start(); // 开始接收数据
    bool stop();
    bool dispose();

    // 接收用户传入的回调函数
    bool setCallback(DatagramReceived callback);

private:
    void startReceive();
    void handleReceive(const boost::system::error_code &error, std::size_t bytes_transferred);
    void raiseError(const std::string &message);

private:
    std::string _bindIP;
    std::string _remoteIP;
    unsigned short _port;

    std::unique_ptr<std::thread> io_thread_; // 用于处理 io_context 的线程
    bool _isWorking = false;

    std::unique_ptr<boost::asio::ip::udp::socket> socket_; // 使用智能指针管理 socket
    std::unique_ptr<boost::asio::io_context> io_context_;

    boost::asio::ip::udp::endpoint remote_endpoint_; // 远端地址
    std::vector<uint8_t> recv_buffer_;               // 接收缓冲区

    DatagramReceived callback_;                      // 自定义回调函数
};

#endif // UDPRECEIVER_H